package com.jcgyl.export.service.Impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import com.jcgyl.export.dao.GoodsDao;
import com.jcgyl.export.dao.TborderlistDao;
import com.jcgyl.export.dao.TbuploadDetailDao;
import com.jcgyl.export.entity.Goods;
import com.jcgyl.export.entity.Tbuploaddetail;
import com.jcgyl.export.mapper.GoodsMapper;
import com.jcgyl.export.mapper.TbuploaddetailMapper;
import com.jcgyl.export.model.SystemConstants;
import com.jcgyl.export.service.GoodsService;
import com.jcgyl.export.service.RedisService;
import com.jcgyl.export.util.entity.Result;

@Service
public class GoodsServiceImpl implements GoodsService {
	@Autowired
	private GoodsDao goodsDao;
	@Autowired
	private TborderlistDao orderlistDao;
	@Autowired
	private TbuploadDetailDao uploadDetailDao;
	@Autowired
	private TbuploaddetailMapper uploaddetailMapper;
	@Autowired
	private GoodsMapper goodsMapper;
	@Autowired
	private RedisService redisService;

	@Override
	public Map<String, Object> findAllGoods(String goodsname, String goodscode, String hscode, int pageSize,
			int pageIndex) {
		int rowCount = goodsDao.findRowCount(goodsname, goodscode, hscode);
		int startIndex = (pageIndex - 1) * pageSize;
		System.out.println(startIndex+':'+pageSize);
		List<Goods> list = goodsDao.findAllGoods(goodsname, goodscode, hscode, startIndex, pageSize);
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("result", list);
		map.put("totalRows", rowCount);
		return map;
	}

	@Override
	public Result addGoods(Goods goods) {
		try {
			goodsMapper.insert(goods);
			//添加到缓存
			redisService.set(SystemConstants.GoodsInfo_Prefix + ":" + goods.getGoodsname(), goods);
			String goodsname = goods.getGoodsname();
			goodsDao.SetIsOk(goodsname);
			return Result.build(0, "数据库添加商品成功");
		} catch (Exception ex) {
			ex.printStackTrace();
			return Result.build(1, "数据库添加商品失败", ex.getMessage());
		}
	}

	@Override
	public Result updateGoods(Goods goods) {
		try {
			goodsMapper.updateByPrimaryKey(goods);
			//添加到缓存
			redisService.set(SystemConstants.GoodsInfo_Prefix + ":" + goods.getGoodsname(), goods);
			return Result.build(0, "修改商品信息成功");
		} catch (Exception ex) {
			ex.printStackTrace();
			return Result.build(1, "修改商品信息失败", ex.getMessage());
		}
	}

	@Override
	public Result deleteGoods(Goods goods) {
		try {
			Integer goodsid=goods.getGoodsid();
			System.out.println(goodsid);
			goodsMapper.deleteByPrimaryKey(goodsid);
			return Result.build(0, "修改商品信息成功");
		} catch (Exception ex) {
			ex.printStackTrace();
			return Result.build(1, "修改商品信息失败", ex.getMessage());
		}
	}

	@Override
	public Goods findGoodsByGoodsName(String goodsname) {
		return  goodsDao.findGoodsByGoodsName(goodsname);
	}

}
